package com.six.controller;

import com.six.domain.Role;
import com.six.domain.User;
import com.six.service.RoleService;
import com.six.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @RequestMapping("/del/{userId}")
    public String del(@PathVariable("userId") Integer userId) {
        userService.del(userId);
        return "redirect:/user/list";
    }

    @RequestMapping("/save")
    public String save(User user, Integer[] roleIds) {
        userService.save(user, roleIds);
        return "redirect:/user/list";
    }

    @RequestMapping("/saveUI")
    public ModelAndView saveUI() {
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("user-add");
        return modelAndView;
    }

    @RequestMapping("/list")
    public ModelAndView list() {
        List<User> userList = userService.list();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList", userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/serch")
    @ResponseBody
    public Map<String, Object> serch(@RequestBody User user, Model model) {
        System.out.println(user.getUsername());
        List<User> userList = userService.serch(user.getUsername());
        for (User user1 : userList) {
            System.out.println(user1);
        }
        Map map = new HashMap();
        map.put("code", 200);
        map.put("userList", userList);
//        model.addAttribute("userList",userList);
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("userList",userList);
//        modelAndView.setViewName("user-list");
        return map;
    }

    @RequestMapping("/serch1/{username}")
    public ModelAndView serch1(@PathVariable String username) {
        List<User> userList = userService.serch(username);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList", userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }
}
